# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2019/8/19 14:15
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
from __future__ import unicode_literals
import uuid

from django.utils.encoding import python_2_unicode_compatible
from django.conf import settings
from django.contrib.auth import get_user_model

from django.db import models


@python_2_unicode_compatible
class MessageQuerySet(models.query.QuerySet):
    def get_conversation(self, sender, recipient):
        """聊天记录，获取两个用户互相发送的消息取并集，用户间的私信会话"""
        qs_one = self.filter(sender=sender, recipient=recipient).select_related('sender', 'recipient')  # A发送给B的信息
        qs_two = self.filter(sender=recipient, recipient=sender).select_related('sender', 'recipient')  # B发送给A的消息
        return qs_one.union(qs_two).order_by("created_at")  # 取并集后按时间排序

    def get_most_recent_conversation(self, recipient):
        """获取最近一次私信活动的用户；recipient传入的是登录用户对象"""
        try:
            qs_sent = self.filter(sender=recipient).select_related('sender', 'recipient')  # 当前登录用户发送的消息
            qs_recieved = self.filter(recipient=recipient).select_related('sender', 'recipient')  # 当前登录用户接受的消息
            qs = qs_sent.union(qs_recieved).latest("created_at")  # 最后一条消息，使用latest，必须在模型的元数据定义ordering

            # 如果登录用户有发送消息，返回消息的接收者
            if qs.sender == recipient:
                return qs.recipient  # 此处的recipient是消息的接受者
            # 否则返回消息的发送者
            return qs.sender
        except self.model.DoesNotExist:
            # 如果模型实例不存在，则返回当前用户。
            # 场景：没有发送消息也没有接收到消息，则会在取并集时报DoesNotExist错误。
            return get_user_model().objects.get(username=recipient.username)


@ python_2_unicode_compatible
class Message(models.Model):

    uuid_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="sent_messages",
                               blank=True, null=True, on_delete=models.SET_NULL, verbose_name="发送者")
    recipient = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="received_messages",
                                  blank=True, null=True, on_delete=models.SET_NULL, verbose_name="接受者")
    message = models.TextField(blank=True, null=True, verbose_name="内容")
    unread = models.BooleanField(default=True, verbose_name="是否未读")
    # 没有updated_at, 私信发送之后不能修改或撤回
    created_at = models.DateTimeField(db_index=True, auto_now_add=True, verbose_name="创建时间")
    objects = MessageQuerySet.as_manager()

    class Meta:
        verbose_name = "私信"
        verbose_name_plural = verbose_name
        ordering = ("-created_at", )
        db_table = "tb_message"

    def __str__(self):
        return self.message

    def mark_as_read(self):
        """
        unread = True 未读
        unread = False 已读
        """
        if self.unread:
            self.unread = False
            self.save()
